﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpreadsheetGear;
using System.IO;
using System.Reflection;
namespace MachiningHelper.ToolFile
{
    public class GCodeExporter
    {
        static string errorFile;
        private static bool TestMode;
        public static bool HdrillMachining(string outputFilepath, string outputFilename, string outputToolfile, MachiningPart part)
        {
            bool IsError = false;
            List<Content> results = new List<Content>();
            List<Content> WriteSeq = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile = Path.Combine(outputFilepath, outputFilename + currentSet.FileExtension);
            ClearBookOldInfo(book);
            results.AddRange(LoadBorder(book, part));
            results.AddRange(LoadHdrill(book, part));
            results.AddRange(LoadFinish(book, part));
            WriteSeq = results.OrderBy(it => it.ID).ToList();
            if (WriteSeq.Exists(Content.IsError))
                IsError = true;
            WriteSeq.RemoveAll(Content.IsErrorOrNull);
            StreamWriter sw = new StreamWriter(outputfile, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq)
            {
                sw.WriteLine(line.Body);
            }
            sw.Close();
            sw.Dispose();
            return IsError;
        }
        public static bool NormalMachining(string outputFilepath, string outputFilename, string outputToolfile, MachiningPart part, bool testMode)
        {
            bool IsError = false;
            TestMode = testMode;
            List<Content> results = new List<Content>();
            List<Content> WriteSeq = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile = Path.Combine(outputFilepath, outputFilename + currentSet.FileExtension);
            errorFile = Path.Combine(outputFilepath, outputFilename);
            ClearBookOldInfo(book);
            results.AddRange(LoadBorder(book, part));
            results.AddRange(LoadVdrill(book, part));
            results.AddRange(LoadHdrill(book, part));
            results.AddRange(LoadSaw(book, part));
            results.AddRange(LoadRoute(book, part));
            results.AddRange(LoadNest(book, part));
            results.AddRange(LoadFinish(book, part));
            WriteSeq = results.OrderBy(it => it.ID).ToList();
            if (WriteSeq.Exists(Content.IsError))
                IsError = true;
            WriteSeq.RemoveAll(Content.IsErrorOrNull);
            StreamWriter sw = new StreamWriter(outputfile, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq)
            {
                sw.WriteLine(line.Body);
            }
            sw.Close();
            sw.Dispose();
            return IsError;
        }
        public static bool NormalMachining(string outputFilepath, string outputFilename, string outputToolfile, List<MachiningPart> parts, bool testMode)
        {
            bool IsError = false;
            TestMode = testMode;
            List<Content> results = new List<Content>();
            List<Content> WriteSeq = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile = Path.Combine(outputFilepath, outputFilename + currentSet.FileExtension);
            errorFile = Path.Combine(outputFilepath, outputFilename);
            foreach (var part in parts)
            {
                List<Content> tempList = new List<Content>();
                ClearBookOldInfo(book);
                tempList.AddRange(LoadBorder(book, part));
                tempList.AddRange(LoadVdrill(book, part));
                tempList.AddRange(LoadHdrill(book, part));
                tempList.AddRange(LoadSaw(book, part));
                tempList.AddRange(LoadRoute(book, part));
                tempList.AddRange(LoadNest(book, part));
                tempList.AddRange(LoadFinish(book, part));
                results.AddRange(tempList.OrderBy(it => it.ID));
            }
            StreamWriter sw = new StreamWriter(outputfile, false, Encoding.GetEncoding("gb2312"));
            WriteSeq = results;
            if (WriteSeq.Exists(Content.IsError))
                IsError = true;
            WriteSeq.RemoveAll(Content.IsErrorOrNull);
            foreach (var line in WriteSeq)
            {
                sw.WriteLine(line.Body);
            }
            sw.Close();
            sw.Dispose();
            return IsError;
        }
        #region  skipper100普通模式生成机代码
        public static bool NormalPartMachining(string outputFilepath, string outputFilename, string outputToolfile, MachiningPart part)
        {
            bool IsError = false;
            List<Content> results = new List<Content>();
            List<Content> WriteSeq = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile = Path.Combine(outputFilepath, outputFilename + currentSet.FileExtension);
            ClearBookOldInfo(book);
            results.AddRange(LoadBorder(book, part));
            results.AddRange(LoadVdrill(book, part));
            results.AddRange(LoadHdrill(book, part));
            results.AddRange(LoadSaw(book, part));
            results.AddRange(LoadRoute(book, part));
            results.AddRange(LoadNest(book, part));
            if (!results.Exists(it => it.ID > 10))
                results.RemoveAll(it => it.ID == 10);
            results.AddRange(LoadFinish(book, part));
            WriteSeq = results.OrderBy(it => it.ID).ToList();
            if (WriteSeq.Exists(Content.IsError))
                IsError = true;
            WriteSeq.RemoveAll(Content.IsErrorOrNull);

            StreamWriter sw = new StreamWriter(outputfile, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq)
            {
                sw.WriteLine(line.Body);
            }
            sw.Close();
            sw.Dispose();
            return IsError;
        }
        #endregion
        #region 双面加工板件面5面6加工合并
        public static bool FlipOnePartMachining(string outputFilepath, string outputFilename, string outputToolfile, MachiningPart partFace5, MachiningPart partFace6)
        {
            bool IsError = false;
            List<Content> results = new List<Content>();
            List<Content> WriteSeq = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile = Path.Combine(outputFilepath, outputFilename + currentSet.FileExtension);
            ClearBookOldInfo(book);

            LoadBorder(book, partFace5);
            results.AddRange(LoadVdrill(book, partFace5));
            results.AddRange(LoadHdrill(book, partFace5));
            results.AddRange(LoadSaw(book, partFace5));
            results.AddRange(LoadRoute(book, partFace5));
            results.AddRange(LoadNest(book, partFace5));

            ClearBookOldInfo(book);
            results.AddRange(LoadBorder(book, partFace6));
            results.AddRange(LoadVdrill(book, partFace6));
            results.AddRange(LoadHdrill(book, partFace6));
            results.AddRange(LoadSaw(book, partFace6));
            results.AddRange(LoadRoute(book, partFace6));
            results.AddRange(LoadNest(book, partFace6));

            if (!results.Exists(it => it.ID > 10))
                results.RemoveAll(it => it.ID == 10);

            results.AddRange(LoadFinish(book, partFace6));
            WriteSeq = results.OrderBy(it => it.ID).ToList();
            if (WriteSeq.Exists(Content.IsError))
                IsError = true;
            WriteSeq.RemoveAll(Content.IsErrorOrNull);
            StreamWriter sw = new StreamWriter(outputfile, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq)
            {
                sw.WriteLine(line.Body);
            }
            sw.Close();
            return IsError;
        }
        #endregion
        #region 双板叠加机加工嵌入，仅用于Skipper100
        public static bool FlipDoublePartMachining(string outputFilepath, string outputFilename1, string outputFilename2, string outputToolfile, MachiningPart part1, MachiningPart part2, BiesseEditorUserData currentData)
        {
            bool IsError = false;
            List<Content> results1 = new List<Content>();
            List<Content> WriteSeq1 = new List<Content>();
            List<Content> results2 = new List<Content>();
            List<Content> WriteSeq2 = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile1 = Path.Combine(outputFilepath, outputFilename1 + currentSet.FileExtension);
            string outputfile2 = Path.Combine(outputFilepath, outputFilename2 + currentSet.FileExtension);
            ClearBookOldInfo(book);
            currentData.SPR = outputfile2;
            List<Content> borderContent = LoadBorder(book, part1);
            if (borderContent.Find(Content.IsCuststr) != null)
                BiesseEditorUserData.SetUserData(borderContent.Find(Content.IsCuststr), currentData);
            results1.AddRange(borderContent);
            results1.AddRange(LoadVdrill(book, part1));
            results1.AddRange(LoadHdrill(book, part1));
            results1.AddRange(LoadSaw(book, part1));
            results1.AddRange(LoadRoute(book, part1));
            results1.AddRange(LoadFinish(book, part1));
            WriteSeq1 = results1.OrderBy(it => it.ID).ToList();


            results2.AddRange(LoadBorder(book, part2));
            List<Content> vdrillContent = LoadVdrill(book, part2);
            CRN.ChangeCRN(vdrillContent, true);
            List<Content> sawContent = LoadSaw(book, part2);
            CRN.ChangeCRN(sawContent, true);
            List<Content> routeContent = LoadRoute(book, part2);
            CRN.ChangeCRN(routeContent, true);
            results2.AddRange(vdrillContent);
            results2.AddRange(LoadHdrillForDoublePart(book, part2));
            results2.AddRange(sawContent);
            results2.AddRange(routeContent);
            //results2.AddRange(LoadNest(book, part2));
            results2.AddRange(LoadFinish(book, part2));
            WriteSeq2 = results2.OrderBy(it => it.ID).ToList();

            if (WriteSeq1.Exists(Content.IsError) | WriteSeq2.Exists(Content.IsError))
                IsError = true;
            WriteSeq1.RemoveAll(Content.IsErrorOrNull);
            WriteSeq2.RemoveAll(Content.IsErrorOrNull);
            StreamWriter sw2 = new StreamWriter(outputfile2, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq2)
            {
                sw2.WriteLine(line.Body);
            }
            sw2.Close();
            StreamWriter sw1 = new StreamWriter(outputfile1, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq1)
            {
                sw1.WriteLine(line.Body);
            }
            sw1.Close();
            return IsError;
        }
        #endregion
        #region 双板合并成一片板加工
        public static bool doublePartFlipOne(string outputFilepath, string outputFilename1, string outputToolfile, MachiningPart part1, MachiningPart part2)
        {
            bool IsError = false;
            List<Content> results1 = new List<Content>();
            List<Content> WriteSeq1 = new List<Content>();
            List<Content> results2 = new List<Content>();
            List<Content> WriteSeq2 = new List<Content>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);
            string outputfile1 = Path.Combine(outputFilepath, outputFilename1 + currentSet.FileExtension);
            ClearBookOldInfo(book);
            List<Content> bordercontent = LoadBorder(book, part1);
            string doublethickness = (double.Parse(part1.Border.PanelThickness) * 2).ToString();
            CRN.doubleThickness(bordercontent.Find(Content.IsLPZ), part1.Border.PanelThickness, doublethickness);
            results1.AddRange(bordercontent);
            results1.AddRange(LoadVdrill(book, part1));
            results1.AddRange(LoadHdrill(book, part1));
            results1.AddRange(LoadSaw(book, part1));
            results1.AddRange(LoadRoute(book, part1));

            LoadBorder(book, part2);
            List<Content> vdrillcontent = LoadVdrill(book, part2);
            CRN.ChangeSide(vdrillcontent);
            List<Content> sawcontent = LoadSaw(book, part2);
            CRN.ChangeSide(sawcontent);
            List<Content> routecontent = LoadRoute(book, part2);
            CRN.ChangeSide(routecontent);
            results1.AddRange(vdrillcontent);
            results1.AddRange(LoadHdrillDoubleFlipOne(book, part2));
            results1.AddRange(sawcontent);
            results1.AddRange(routecontent);
            //去除wait动作
            if (!results1.Exists(it => it.ID > 10))
                results1.RemoveAll(it => it.ID == 10);

            results1.AddRange(LoadFinish(book, part2));
            WriteSeq1 = results1.OrderBy(it => it.ID).ToList();
            if (WriteSeq1.Exists(Content.IsError) | WriteSeq2.Exists(Content.IsError))
                IsError = true;
            WriteSeq1.RemoveAll(Content.IsErrorOrNull);

            StreamWriter sw1 = new StreamWriter(outputfile1, false, Encoding.GetEncoding("gb2312"));
            foreach (var line in WriteSeq1)
            {
                sw1.WriteLine(line.Body);
            }
            sw1.Close();
            return IsError;
        }
        #endregion
        #region 填入加工数据前，先清除刀具文件B列数据
        private static void ClearBookOldInfo(IWorkbook book)
        {
            string[] names = new string[]{"Finish Sequence",
                                         "Nest Sequence",
                                         "Routing Sequence",
                                         "Sawing Sequence",
                                         "Horizontal Drilling Sequence",
                                         "Vertical Drilling Sequence",
                                         "Border Sequence"};
            foreach (string name in names)
            {
                book.Worksheets[name].Cells[0, 1].EntireColumn.Clear();
            }
        }
        #endregion
        #region 填写刀具文件B列，输出D列
        private static List<Content> LoadBorder(IWorkbook book, MachiningPart part)
        {
            var borderCells = book.Worksheets["Border Sequence"].Cells;
            List<Content> rowContent = new List<Content>();
            borderCells[0, 1].Value = part.Border.PanelWidth;
            borderCells[1, 1].Value = part.Border.PanelLength;
            borderCells[2, 1].Value = part.Border.PanelThickness;
            borderCells[3, 1].Value = part.Border.RunField;
            borderCells[4, 1].Value = part.Border.CurrentFace;
            borderCells[5, 1].Value = part.Border.PreviousFace;
            borderCells[6, 1].Value = part.Border.CurrentZoneName;
            borderCells[7, 1].Value = part.Border.FieldOffsetX;
            borderCells[8, 1].Value = part.Border.FieldOffsetY;
            borderCells[9, 1].Value = part.Border.FieldOffsetZ;
            borderCells[10, 1].Value = part.Border.JobName;
            borderCells[11, 1].Value = part.Border.ItemNumber;
            borderCells[12, 1].Value = part.Border.FileName;
            borderCells[13, 1].Value = part.Border.Face6FileName;
            borderCells[14, 1].Value = part.Border.Description;
            borderCells[15, 1].Value = part.Border.PartQty;
            borderCells[16, 1].Value = part.Border.CutPartWidth;
            borderCells[17, 1].Value = part.Border.CutPartLength;
            borderCells[18, 1].Value = part.Border.MaterialName;
            borderCells[19, 1].Value = part.Border.MaterialCode;
            borderCells[20, 1].Value = part.Border.Edge1;
            borderCells[21, 1].Value = part.Border.Edge2;
            borderCells[22, 1].Value = part.Border.Edge3;
            borderCells[23, 1].Value = part.Border.Edge4;
            borderCells[24, 1].Value = part.Border.PartComments;
            borderCells[25, 1].Value = part.Border.ProductDescription;
            borderCells[26, 1].Value = part.Border.ProductQty;
            borderCells[27, 1].Value = part.Border.ProductWidth;
            borderCells[28, 1].Value = part.Border.ProductHeight;
            borderCells[29, 1].Value = part.Border.ProductDepth;
            borderCells[30, 1].Value = part.Border.ProductComments;
            borderCells[31, 1].Value = part.Border.PerfectGrain;
            borderCells[32, 1].Value = part.Border.GrainFlag;
            borderCells[33, 1].Value = part.Border.PartCounter;
            borderCells[34, 1].Value = part.Border.FoundHdrill;
            borderCells[35, 1].Value = part.Border.FoundVdrill;
            borderCells[36, 1].Value = part.Border.FoundVdrillFace6;
            borderCells[37, 1].Value = part.Border.FoundRouting;
            borderCells[38, 1].Value = part.Border.FoundRoutingFace6;
            borderCells[39, 1].Value = part.Border.FoundSawing;
            borderCells[40, 1].Value = part.Border.FoundSawingFace6;
            borderCells[41, 1].Value = part.Border.FoundFace6Program;
            borderCells[42, 1].Value = part.Border.FoundNesting;
            borderCells[43, 1].Value = part.Border.FirstPassDepth;
            borderCells[44, 1].Value = part.Border.SpoilBoardPenetration;
            borderCells[45, 1].Value = part.Border.BasePoint;
            borderCells[46, 1].Value = part.Border.MachinePoint;
            borderCells[47, 1].Value = part.Border.MfgDataPath;
            borderCells[48, 1].Value = part.Border.MaterialType;
            borderCells[49, 1].Value = part.Border.EdgeFileNames1;
            borderCells[50, 1].Value = part.Border.EdgeFileNames2;
            borderCells[51, 1].Value = part.Border.EdgeFileNames3;
            borderCells[52, 1].Value = part.Border.EdgeFileNames4;
            borderCells[53, 1].Value = part.Border.EdgeBarCodes1;
            borderCells[54, 1].Value = part.Border.EdgeBarCodes2;
            borderCells[55, 1].Value = part.Border.EdgeBarCodes3;
            borderCells[56, 1].Value = part.Border.EdgeBarCodes4;
            borderCells[57, 1].Value = part.Border.A58;
            borderCells[58, 1].Value = part.Border.A59;
            borderCells[59, 1].Value = part.Border.A60;
            borderCells[60, 1].Value = part.Border.A61;
            borderCells[61, 1].Value = part.Border.A62;
            borderCells[62, 1].Value = part.Border.A63;
            borderCells[63, 1].Value = part.Border.A64;
            borderCells[64, 1].Value = part.Border.A65;
            borderCells[65, 1].Value = part.Border.A66;
            borderCells[66, 1].Value = part.Border.A67;
            borderCells[67, 1].Value = part.Border.A68;
            borderCells[69, 1].Value = part.Border.Edge1Thickness;
            borderCells[70, 1].Value = part.Border.Edge2Thickness;
            borderCells[71, 1].Value = part.Border.Edge3Thickness;
            borderCells[72, 1].Value = part.Border.Edge4Thickness;
            int i = 0;
            while (WriteError(borderCells[i, 3]) != "[END]")
            {
                rowContent.Add(Content.myContent(borderCells[i, 3].Text));
                i++;
            }
            return rowContent;
        }
        private static List<Content> LoadVdrill(IWorkbook book, MachiningPart part)
        {
            var VdrillCells = book.Worksheets["Vertical Drilling Sequence"].Cells;
            List<Content> VdrillContent = new List<Content>();
            int index = 0;
            foreach (var vdrill in part.Vdirlls)
            {
                index++;
                VdrillCells[0, 1].Value = vdrill.VDrillX;
                VdrillCells[1, 1].Value = vdrill.VDrillY;
                VdrillCells[2, 1].Value = vdrill.VDrillZ;
                VdrillCells[3, 1].Value = vdrill.VDrillX_Offset;
                VdrillCells[4, 1].Value = vdrill.VDrillY_Offset;
                VdrillCells[5, 1].Value = vdrill.VDrillDiameter;
                VdrillCells[6, 1].Value = vdrill.VDrillToolName;
                VdrillCells[7, 1].Value = vdrill.VDrillFeedSpeed;
                VdrillCells[8, 1].Value = vdrill.VDrillEntrySpeed;
                VdrillCells[9, 1].Value = vdrill.VDrillBitType;
                VdrillCells[10, 1].Value = vdrill.VDrillFirstDrillDone;
                VdrillCells[11, 1].Value = vdrill.VDrillPreviousToolName;
                VdrillCells[12, 1].Value = vdrill.VDrillCounter;
                PrintCode(book, string.Format("{0}-{1}-{2}", part.Border.CurrentZoneName, "Vdrill", index));
                for (int i = 0; i < 2000; i++)
                {
                    string content = WriteError(VdrillCells[i, 3]);
                    if (content == "[END]")
                        break;
                    if (content == "[VDRILL LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = WriteError(VdrillCells[x, 3]);
                            if (content == "[END VDRILL LOOP]")
                            {
                                i = x;
                                break;
                            }
                            VdrillContent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }
            }
            return VdrillContent;
        }
        private static List<Content> LoadHdrill(IWorkbook book, MachiningPart part)
        {
            IRange HdrillCells = book.Worksheets["Horizontal Drilling Sequence"].Cells;
            IRange BorderCells = book.Worksheets["Border Sequence"].Cells;
            List<Content> HdrillContent = new List<Content>();
            int index = 0;
            foreach (var hdrill in part.Hdrills)
            {
                index++;
                HdrillCells[0, 1].Value = hdrill.HDrillX;
                HdrillCells[1, 1].Value = hdrill.HDrillY;
                HdrillCells[2, 1].Value = hdrill.HDrillZ;
                HdrillCells[3, 1].Value = hdrill.HDrillDiameter;
                HdrillCells[4, 1].Value = hdrill.HDrillToolName;
                HdrillCells[5, 1].Value = hdrill.HDrillFeedSpeed;
                HdrillCells[6, 1].Value = hdrill.HDrillEntrySpeed;
                HdrillCells[7, 1].Value = hdrill.HDrillBitType;
                HdrillCells[8, 1].Value = hdrill.HDrillFirstDrillDone;
                HdrillCells[9, 1].Value = hdrill.HDrillPreviousToolName;
                HdrillCells[10, 1].Value = hdrill.HDrillNextToolName;
                HdrillCells[11, 1].Value = hdrill.HDrillCounter;
                BorderCells[4, 1].Value = hdrill.CurrentFace;
                BorderCells[5, 1].Value = hdrill.PreviousFace;
                PrintCode(book, string.Format("{0}-{1}-{2}", part.Border.CurrentZoneName, "Hdrill", index));
                for (int i = 0; i < 2000; i++)
                {
                    string content = WriteError(HdrillCells[i, 3]);
                    if (content == "[END]")
                        break;
                    if (content == "[HDRILL LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = WriteError(HdrillCells[x, 3]);
                            if (content == "[END HDRILL LOOP]")
                            {
                                i = x;
                                break;
                            }
                            HdrillContent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }

            }
            return HdrillContent;
        }
        #region 双板加工，PMOD=2使用
        private static List<Content> LoadHdrillForDoublePart(IWorkbook book, MachiningPart part)
        {
            IRange HdrillCells = book.Worksheets["Horizontal Drilling Sequence"].Cells;
            IRange BorderCells = book.Worksheets["Border Sequence"].Cells;
            List<Content> HdrillContent = new List<Content>();
            foreach (var hdrill in part.Hdrills)
            {
                List<Content> hdrillcontent = new List<Content>();
                HdrillCells[0, 1].Value = hdrill.HDrillX;
                HdrillCells[1, 1].Value = hdrill.HDrillY;
                HdrillCells[2, 1].Value = hdrill.HDrillZ;
                HdrillCells[3, 1].Value = hdrill.HDrillDiameter;
                HdrillCells[4, 1].Value = hdrill.HDrillToolName;
                HdrillCells[5, 1].Value = hdrill.HDrillFeedSpeed;
                HdrillCells[6, 1].Value = hdrill.HDrillEntrySpeed;
                HdrillCells[7, 1].Value = hdrill.HDrillBitType;
                HdrillCells[8, 1].Value = hdrill.HDrillFirstDrillDone;
                HdrillCells[9, 1].Value = hdrill.HDrillPreviousToolName;
                HdrillCells[10, 1].Value = hdrill.HDrillNextToolName;
                HdrillCells[11, 1].Value = hdrill.HDrillCounter;
                BorderCells[4, 1].Value = hdrill.CurrentFace;
                BorderCells[5, 1].Value = hdrill.PreviousFace;
                for (int i = 0; i < 2000; i++)
                {
                    string content = HdrillCells[i, 3].Text;
                    if (content == "[END]")
                        break;
                    if (content == "[HDRILL LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = HdrillCells[x, 3].Text;
                            if (content == "[END HDRILL LOOP]")
                            {
                                i = x;
                                break;
                            }
                            hdrillcontent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }
                hdrillcontent.RemoveAll(Content.IsErrorOrNull);
                if (hdrillcontent.Exists(Content.IsSide1))
                {
                    CRN.changeSide(hdrillcontent.Find(Content.IsSide1), "1", "3");
                    CRN.ChangeCRN(hdrillcontent, true);
                }
                else if (hdrillcontent.Exists(Content.IsSide3))
                {
                    CRN.changeSide(hdrillcontent.Find(Content.IsSide3), "3", "1");
                    CRN.ChangeCRN(hdrillcontent, true);
                }
                else if (hdrillcontent.Exists(Content.IsSide2))
                    CRN.Changecrn(hdrillcontent.Find(Content.IsCRN), true);
                else if (hdrillcontent.Exists(Content.IsSide4))
                    CRN.Changecrn(hdrillcontent.Find(Content.IsCRN), true);
                HdrillContent.AddRange(hdrillcontent);
            }
            return HdrillContent;
        }
        #endregion
        #region 双板加工，合并成一片板
        private static List<Content> LoadHdrillDoubleFlipOne(IWorkbook book, MachiningPart part)
        {
            IRange HdrillCells = book.Worksheets["Horizontal Drilling Sequence"].Cells;
            IRange BorderCells = book.Worksheets["Border Sequence"].Cells;
            List<Content> HdrillContent = new List<Content>();

            foreach (var hdrill in part.Hdrills)
            {
                List<Content> hdrillcontent = new List<Content>();
                HdrillCells[0, 1].Value = hdrill.HDrillX;
                HdrillCells[1, 1].Value = hdrill.HDrillY;
                HdrillCells[2, 1].Value = hdrill.HDrillZ;
                HdrillCells[3, 1].Value = hdrill.HDrillDiameter;
                HdrillCells[4, 1].Value = hdrill.HDrillToolName;
                HdrillCells[5, 1].Value = hdrill.HDrillFeedSpeed;
                HdrillCells[6, 1].Value = hdrill.HDrillEntrySpeed;
                HdrillCells[7, 1].Value = hdrill.HDrillBitType;
                HdrillCells[8, 1].Value = hdrill.HDrillFirstDrillDone;
                HdrillCells[9, 1].Value = hdrill.HDrillPreviousToolName;
                HdrillCells[10, 1].Value = hdrill.HDrillNextToolName;
                HdrillCells[11, 1].Value = hdrill.HDrillCounter;
                BorderCells[4, 1].Value = hdrill.CurrentFace;
                BorderCells[5, 1].Value = hdrill.PreviousFace;
                for (int i = 0; i < 2000; i++)
                {
                    string content = HdrillCells[i, 3].Text;
                    if (content == "[END]")
                        break;
                    if (content == "[HDRILL LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = HdrillCells[x, 3].Text;
                            if (content == "[END HDRILL LOOP]")
                            {
                                i = x;
                                break;
                            }
                            hdrillcontent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }
                hdrillcontent.RemoveAll(Content.IsErrorOrNull);
                if (hdrillcontent.Exists(Content.IsSide1))
                {
                    CRN.changeSide(hdrillcontent.Find(Content.IsSide1), "1", "3");
                    CRN.ChangeCRN(hdrillcontent, false);
                }
                else if (hdrillcontent.Exists(Content.IsSide3))
                {
                    CRN.changeSide(hdrillcontent.Find(Content.IsSide3), "3", "1");
                    CRN.ChangeCRN(hdrillcontent, false);
                }
                else if (hdrillcontent.Exists(Content.IsSide2))
                    CRN.Changecrn(hdrillcontent.Find(Content.IsCRN), false);
                else if (hdrillcontent.Exists(Content.IsSide4))
                    CRN.Changecrn(hdrillcontent.Find(Content.IsCRN), false);
                HdrillContent.AddRange(hdrillcontent);
            }
            return HdrillContent;
        }
        #endregion 双板加工，合并成一片板
        private static List<Content> LoadSaw(IWorkbook book, MachiningPart part)
        {
            IRange SawCells = book.Worksheets["Sawing Sequence"].Cells;
            List<Content> SawContent = new List<Content>();
            int index = 0;
            foreach (var saw in part.Saws)
            {
                index++;
                SawCells[0, 1].Value = saw.SawStartX;
                SawCells[1, 1].Value = saw.SawStartY;
                SawCells[2, 1].Value = saw.SawStartZ;
                SawCells[3, 1].Value = saw.SawEndX;
                SawCells[4, 1].Value = saw.SawEndY;
                SawCells[5, 1].Value = saw.SawEndZ;
                SawCells[6, 1].Value = saw.SawKerfWidth;
                SawCells[7, 1].Value = saw.SawToolName;
                SawCells[8, 1].Value = saw.SawPreviousToolName;
                SawCells[9, 1].Value = saw.SawNextToolName;
                SawCells[10, 1].Value = saw.SawFeedSpeed;
                SawCells[11, 1].Value = saw.SawToolComp;
                SawCells[12, 1].Value = saw.SawStartOffsetX;
                SawCells[13, 1].Value = saw.SawStartOffsetY;
                SawCells[14, 1].Value = saw.SawEndOffsetX;
                SawCells[15, 1].Value = saw.SawEndOffsetY;
                PrintCode(book, string.Format("{0}-{1}-{2}", part.Border.CurrentZoneName, "SAW", index));
                for (int i = 0; i < 2000; i++)
                {
                    string content = WriteError(SawCells[i, 3]);
                    if (content == "[END]")
                        break;
                    if (content == "[SAW LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = WriteError(SawCells[x, 3]);
                            if (content == "[END SAW LOOP]")
                            {
                                i = x;
                                break;
                            }
                            SawContent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }
            }
            return SawContent;
        }
        private static List<Content> LoadRoute(IWorkbook book, MachiningPart part)
        {
            IRange RouteCells = book.Worksheets["Routing Sequence"].Cells;
            List<Content> routeContent = new List<Content>();
            int rindex = 0;
            //RouteOptimize.CutOffRoute(part);//铣透后移
            foreach (var oneroute in part.Routes)
            {
                rindex++;
                LoadRouteSeq(RouteCells, oneroute.SetMillSeq);
                PrintCode(book, string.Format("{0}{1}{2}", part.Border.CurrentZoneName, "Route", rindex));
                for (int i = 0; i < 2000; i++)
                {
                    string content = WriteError(RouteCells[i, 3]);
                    if (content == "[END]")
                        break;
                    if (content == "[SETMILL LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = WriteError(RouteCells[x, 3]);
                            if (content == "[END SETMILL LOOP]")
                            {
                                int oindex = 0;
                                foreach (var route in oneroute.RouteSeqs)
                                {
                                    oindex++;
                                    LoadRouteSeq(RouteCells, route);
                                    PrintCode(book, string.Format("{0}-{1}-{2}-{3}", part.Border.CurrentZoneName, "Route", rindex, oindex));
                                    for (int y = x + 1; y < 2000; y++)
                                    {
                                        content = WriteError(RouteCells[y, 3]);
                                        if (content == "[END]")
                                        {
                                            i = y - 1;
                                            break;
                                        }
                                        if (content == "[ROUTE LOOP]")
                                        {
                                            for (int z = y + 1; z < 2000; z++)
                                            {
                                                content = WriteError(RouteCells[z, 3]);
                                                if (content == "[END ROUTE LOOP]")
                                                {
                                                    y = z;
                                                    break;
                                                }
                                                routeContent.Add(Content.myContent(content));
                                            }
                                        }
                                        else { }
                                    }
                                }
                                break;
                            }
                            routeContent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }
            }
            return routeContent;
        }
        private static List<Content> LoadNest(IWorkbook book, MachiningPart part)
        {
            IRange RouteCells = book.Worksheets["Nest Sequence"].Cells;
            List<Content> nestContent = new List<Content>();
            foreach (var oneroute in part.Nests)
            {
                LoadRouteSeq(RouteCells, oneroute.SetMillSeq);
                for (int i = 0; i < 2000; i++)
                {
                    string content = RouteCells[i, 3].Text;
                    if (content == "[END]")
                        break;
                    if (content == "[SETMILL LOOP]")
                    {
                        for (int x = i + 1; x < 2000; x++)
                        {
                            content = RouteCells[x, 3].Text;
                            if (content == "[END SETMILL LOOP]")
                            {
                                foreach (var route in oneroute.RouteSeqs)
                                {
                                    LoadRouteSeq(RouteCells, route);
                                    for (int y = x + 1; y < 2000; y++)
                                    {
                                        content = RouteCells[y, 3].Text;
                                        if (content == "[END]")
                                        {
                                            i = y - 1;
                                            break;
                                        }
                                        if (content == "[ROUTE LOOP]")
                                        {
                                            for (int z = y + 1; z < 2000; z++)
                                            {
                                                content = RouteCells[z, 3].Text;
                                                if (content == "[END ROUTE LOOP]")
                                                {
                                                    y = z;
                                                    break;
                                                }
                                                nestContent.Add(Content.myContent(content));
                                            }
                                        }
                                        else { }
                                    }
                                }
                                break;
                            }
                            nestContent.Add(Content.myContent(content));
                        }
                    }
                    else { }
                }
            }
            return nestContent;
        }
        private static List<Content> LoadFinish(IWorkbook book, MachiningPart part)
        {
            IRange finishCells = book.Worksheets["Finish Sequence"].Cells;
            List<Content> finishContent = new List<Content>();
            finishCells[0, 1].Value = part.Finish.PodX;
            finishCells[1, 1].Value = part.Finish.PodY1;
            finishCells[2, 1].Value = part.Finish.PodY2;
            finishCells[3, 1].Value = part.Finish.PodY3;
            int i = 0;
            while (finishCells[i, 3].Text != "[END]")
            {
                finishContent.Add(Content.myContent(finishCells[i, 3].Text));
                i++;
            }
            return finishContent;

        }
        private static void LoadRouteSeq(IRange RouteCells, RouteOneSeq CurrentSeq)
        {
            RouteCells[0, 1].Value = CurrentSeq.RouteSetMillX;
            RouteCells[1, 1].Value = CurrentSeq.RouteSetMillY;
            RouteCells[2, 1].Value = CurrentSeq.RouteSetMillZ;
            RouteCells[3, 1].Value = CurrentSeq.RouteStartOffsetX;
            RouteCells[4, 1].Value = CurrentSeq.RouteStartOffsetY;
            RouteCells[5, 1].Value = CurrentSeq.RouteDiameter;
            RouteCells[6, 1].Value = CurrentSeq.RouteToolName;
            RouteCells[7, 1].Value = CurrentSeq.RoutePreviousToolName;
            RouteCells[8, 1].Value = CurrentSeq.RouteNextToolName;
            RouteCells[9, 1].Value = CurrentSeq.RouteFeedSpeed;
            RouteCells[10, 1].Value = CurrentSeq.RouteEntrySpeed;
            RouteCells[11, 1].Value = CurrentSeq.RouteBitType;
            RouteCells[12, 1].Value = CurrentSeq.RouteRotation;
            RouteCells[13, 1].Value = CurrentSeq.RouteToolComp;
            RouteCells[14, 1].Value = CurrentSeq.RouteX;
            RouteCells[15, 1].Value = CurrentSeq.RouteY;
            RouteCells[16, 1].Value = CurrentSeq.RouteZ;
            RouteCells[17, 1].Value = CurrentSeq.RouteEndOffsetX;
            RouteCells[18, 1].Value = CurrentSeq.RouteEndOffsetY;
            RouteCells[19, 1].Value = CurrentSeq.RouteBulge;
            RouteCells[20, 1].Value = CurrentSeq.RouteRadius;
            RouteCells[21, 1].Value = CurrentSeq.RouteCenterX;
            RouteCells[22, 1].Value = CurrentSeq.RouteCenterY;
            RouteCells[23, 1].Value = CurrentSeq.RouteNextX;
            RouteCells[24, 1].Value = CurrentSeq.RouteNextY;
            RouteCells[25, 1].Value = CurrentSeq.RoutePreviousX;
            RouteCells[26, 1].Value = CurrentSeq.RoutePreviousY;
            RouteCells[27, 1].Value = CurrentSeq.RoutePreviousZ;
            RouteCells[28, 1].Value = CurrentSeq.RouteBulgeNext;
            RouteCells[29, 1].Value = CurrentSeq.RouteSetMillCounter;
            RouteCells[30, 1].Value = CurrentSeq.RouteVectorCounter;
            RouteCells[31, 1].Value = CurrentSeq.RouteVectorCount;
            RouteCells[32, 1].Value = CurrentSeq.RouteAngle;
            RouteCells[33, 1].Value = CurrentSeq.RoutePreviousFeedSpeed;
            RouteCells[34, 1].Value = CurrentSeq.A35;
            RouteCells[37, 1].Value = CurrentSeq.MaxZValue;
            RouteCells[38, 1].Value = CurrentSeq.Sequence;
            RouteCells[39, 1].Value = CurrentSeq.IsCenterOnly;
            RouteCells[40, 1].Value = CurrentSeq.IsExtraOnOtherFace;
        }

        #endregion

        public static void skipper100Test(string file1, string file2, string outputToolfile, string outputPath)
        {
            FileInfo fi1 = new FileInfo(file1);
            FileInfo fi2 = new FileInfo(file2);

            SkipperEngine skipper = new SkipperEngine(file1, file2);
            skipper.DoublePartFlipOne();
            List<Content> result = new List<Content>();

            List<string> results = new List<string>();
            IWorkbook book = Factory.GetWorkbook(outputToolfile);
            ColToolFile currentSet = ColToolFile.LoadToolFile(outputToolfile);

            ClearBookOldInfo(book);

            result.AddRange(LoadBorder(book, skipper.part2));
            result.AddRange(LoadVdrill(book, skipper.part2));
            result.AddRange(LoadHdrill(book, skipper.part2));
            result.AddRange(LoadRoute(book, skipper.part2));
            result.AddRange(LoadSaw(book, skipper.part2));

            ClearBookOldInfo(book);
            LoadBorder(book, skipper.part1);
            result.AddRange(LoadVdrill(book, skipper.part1));
            result.AddRange(LoadHdrill(book, skipper.part1));
            result.AddRange(LoadRoute(book, skipper.part1));
            result.AddRange(LoadSaw(book, skipper.part1));
            result = result.OrderBy(it => it.ID).ToList();
            if (!result.Exists(it => it.ID > 10))
                result.RemoveAll(it => it.ID == 10);
            result.AddRange(LoadFinish(book, skipper.part1));

            result.ForEach(it => results.Add(it.Body));
            File.WriteAllLines(Path.Combine(outputPath, fi1.Name + fi2.Name + currentSet.FileExtension), results.ToArray(), Encoding.GetEncoding("gb2312"));
        }
        private static string WriteError(IRange range)
        {
            if (range.ValueType == SpreadsheetGear.ValueType.Error)
                range.Worksheet.Workbook.SaveAs(errorFile + range.Worksheet.Name + range.Address + ".xlsx", FileFormat.OpenXMLWorkbook);
            return range.Text;
        }
        private static void PrintCode(IWorkbook book, string filename)
        {
            if (!TestMode)
                return;
            if (!Directory.Exists(errorFile))
                Directory.CreateDirectory(errorFile);
            book.SaveAs(Path.Combine(errorFile, filename + ".xlsx"), FileFormat.OpenXMLWorkbook);
        }
    }

}
